
import imaplib
import email
import os
from email.header import decode_header
import time
import threading

# 你的邮箱登录信息
username = "1517637121@qq.com"
password = "yjtlnhpblstojjab"

def decode_mime_words(s):
    """解码MIME编码的字符串"""
    decoded_string = ''
    for word, encoding in decode_header(s):
        if encoding:
            try:
                decoded_string += word.decode(encoding)
            except (UnicodeDecodeError, AttributeError):
                decoded_string += word if isinstance(word, str) else str(word)
        else:
            decoded_string += word if isinstance(word, str) else str(word)
    return decoded_string


def check_email():
    try:
        # 连接到Gmail的IMAP服务器
        print("Connecting to the IMAP server...")
        mail = imaplib.IMAP4_SSL("imap.qq.com", 993)
        mail.login(username, password)
        print("Logged in successfully")
        mail.select("inbox")
        print("Mailbox selected")

        # 搜索未读邮件
        status, messages = mail.search(None, '(UNSEEN)')
        mail_ids = messages[0].split()
        print(f"Found {len(mail_ids)} unread emails")

        for mail_id in mail_ids:
            status, msg_data = mail.fetch(mail_id, "(RFC822)")
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_bytes(response_part[1])
                    email_from = msg["From"]

                    # 进行调试，打印出邮件头部信息
                    print(f"Email ID: {mail_id}")
                    print(f"Email Headers: {msg.items()}")

                    if email_from:
                        email_from = decode_mime_words(email_from)
                        print(f"Decoded From: {email_from}")
                    else:
                        print("From field is empty")

                    # 检查发件人是否是特定用户
                    if "1517637121@qq.com" in email_from:
                        print("收到特定发件人的邮件，准备关机")
                        shut_down()
                        # 将邮件标记为已读
                        mail.store(mail_id, '+FLAGS', '\\Seen')
                        print(f"Email ID {mail_id.decode()} marked as read.")

        mail.logout()
        print("Logged out successfully")
    except imaplib.IMAP4.error as imap_error:
        print(f"IMAP error occurred: {imap_error}")
    except Exception as e:
        print(f"检查邮件时出错: {e}")
        raise


def shut_down():
    try:
        # 执行关机命令
        if os.name == 'nt':
            print("Shutting down the system (Windows)...")
            os.system("shutdown /s /t 100")
        else:
            print("Shutting down the system (Unix)...")
            os.system("sudo shutdown now")
    except Exception as e:
        print(f"关机时出错: {e}")
        raise

def shut_down():
    try:
        # 执行关机命令
        if os.name == 'nt':
            print("Shutting down the system (Windows)...")
            os.system("shutdown /s /t 1")
        else:
            print("Shutting down the system (Unix)...")
            os.system("sudo shutdown now")
    except Exception as e:
        print(f"关机时出错: {e}")
        raise


def start_email_listener():
    while True:
        check_email()
        # 每隔60秒检查一次
        time.sleep(60)


if __name__ == "__main__":
    # 创建并启动监听线程
    email_listener_thread = threading.Thread(target=start_email_listener)
    email_listener_thread.daemon = True
    email_listener_thread.start()

    # 主线程继续运行其他任务或保持运行
    while True:
        time.sleep(1)
